package com.gxa.employment.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 * @Author:
 * @DateTime: 2025/1/17 15:36
 **/
@WebFilter(urlPatterns = "/*")
public class CORSFilter implements Filter {
    /**
     * 过滤器要做
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //类型强转（不然不能调用方法）
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;


        //接受任意源（位置）的请求        主要是跨域问题
        resp.setHeader("Access-Control-Allow-Origin", "*");
        //接受任意请求方式
        resp.setHeader("Access-Control-Allow-Methods", "*");
        //最大存活时间
        resp.setHeader("Access-Control-Max-Age", "3600");
        //接受任意请求头
        resp.setHeader("Access-Control-Allow-Headers", "*");
        //允许cookie
        resp.setHeader("Access-Control-Allow-Credentials", "true");

        //前端发送ajax/axios请求时，先通过这个进行判断状态（是否可以正常通信）
        if ("OPTIONS".equals(req.getMethod())) {
            resp.setStatus(HttpServletResponse.SC_OK);
        }

        //如果有下一个，所有都要进行过滤
        filterChain.doFilter(servletRequest, servletResponse);

    }
}
